package com.bmps.springcloud.insuredmicroservice.service.rabbitmq.production;

import com.bmps.springcloud.insuredmicroservice.config.rabbitmq.RabbitConfig;
import com.bmps.springcloud.insuredmicroservice.model.rabbitmq.PolicyDataEx;
import com.bmps.springcloud.insuredmicroservice.model.rabbitmq.RabbitPolicyModel;
import com.bmps.springcloud.insuredmicroservice.util.amqp.DateUtils;
import com.bmps.springcloud.insuredmicroservice.util.mail.MailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;


/**
 * @description: 消息发送服务
 * @author: Jacob
 * @date: 2019/12/23  16:50
 **/
@Service
public class AcceptProducerServiceImpl implements AcceptProducerService {

    private final Logger logger = LoggerFactory.getLogger(AcceptProducerServiceImpl.class);

    private final RabbitTemplate rabbitTemplate;
    private final MailUtil mailUtil;

    public AcceptProducerServiceImpl(RabbitTemplate rabbitTemplate, MailUtil mailUtil) {
        this.rabbitTemplate = rabbitTemplate;
        this.mailUtil = mailUtil;
    }

    @Value("${customize.routing}")
    @NotBlank
    private String acceptRouting;

    @Override
    public void sendMessage(RabbitPolicyModel rabbitPolicyModel) {
        rabbitPolicyModel.setSendTime(System.currentTimeMillis());

        logger.info("开始发送时间: " + DateUtils.localDateTimeToString(LocalDateTime.now())
                + ",保单号: " + rabbitPolicyModel.getContno()
                + ",发送内容: " + rabbitPolicyModel.toString());

        PolicyDataEx policyDataEx = new PolicyDataEx();
        policyDataEx.setId(rabbitPolicyModel.getContno());
        policyDataEx.setMessage(rabbitPolicyModel.toString());
        try {
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_bmps_ACCEPT, acceptRouting, rabbitPolicyModel, policyDataEx);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("【消息队列】生产者发送消息异常，异常信息为：" + e.getMessage());
            mailUtil.sendMail("【消息队列】生产者发送消息异常", "异常信息为:" + e.getMessage());
        }
    }
}
